extends Node2D

@export var damage = 12
@export var attack_cooldown = 1.0  # 攻击冷却时间（秒）
@export var search_radius = 300.0  # 搜索半径
@export var projectile_speed = 350.0  # 冰锥速度
@export var slow_effect = 0.5  # 减速效果（移动速度乘数）
@export var slow_duration = 2.0  # 减速持续时间（秒）
@export var freeze_chance = 0.2  # 冰冻几率

@onready var attack_timer = $AttackTimer
@onready var animation_player = $AnimationPlayer

var owner_player = null  # 持有此武器的玩家引用
var target_direction = Vector2.RIGHT  # 默认方向

func _ready():
	attack_timer.wait_time = attack_cooldown
	attack_timer.one_shot = false  # 设置为重复
	attack_timer.start()
	
	# 确保有动画播放器
	if not animation_player:
		print("WARNING: IceWand missing AnimationPlayer!")

func set_owner_player(player_node):
	owner_player = player_node

func _on_attack_timer_timeout():
	find_and_attack_enemy()

func find_and_attack_enemy():
	var closest_enemy = null
	var min_distance_sq = search_radius * search_radius  # 使用平方距离提高效率
	
	# 获取场景树中"enemies"组内的所有敌人
	var enemies = get_tree().get_nodes_in_group("enemies")
	
	for enemy in enemies:
		# 确保敌人有效且未被标记为删除
		if is_instance_valid(enemy) and enemy.has_method("take_damage"):
			var distance_sq = global_position.distance_squared_to(enemy.global_position)
			if distance_sq < min_distance_sq:
				min_distance_sq = distance_sq
				closest_enemy = enemy
	
	if closest_enemy:
		attack(closest_enemy)

func attack(target_enemy):
	# 计算方向
	target_direction = (target_enemy.global_position - global_position).normalized()
	
	# 创建冰锥实例
	var ice_spike = preload("res://IceSpikeProjectile.tscn").instantiate()
	get_tree().get_root().add_child(ice_spike)
	
	# 设置冰锥属性
	ice_spike.global_position = global_position
	ice_spike.direction = target_direction
	ice_spike.speed = projectile_speed
	ice_spike.damage = damage
	ice_spike.slow_effect = slow_effect
	ice_spike.slow_duration = slow_duration
	ice_spike.freeze_chance = freeze_chance
	
	# 应用暴击（如果玩家有暴击属性）
	if owner_player and owner_player.has_method("get_crit_info"):
		var crit_info = owner_player.get_crit_info()
		if randf() < crit_info.chance:
			ice_spike.damage *= crit_info.multiplier
			ice_spike.is_critical = true
	
	# 播放攻击动画（如果有）
	if animation_player and animation_player.has_animation("attack"):
		animation_player.play("attack")
	
	print(name, " 发射冰锥攻击 ", target_enemy.name)

# 由Player的apply_upgrade函数调用
func upgrade_stat(stat_name, value):
	match stat_name:
		"damage":
			damage += value
			print(name, " 伤害提升至: ", damage)
		"speed":  # 减少冷却时间
			attack_cooldown = max(0.1, attack_cooldown - value)  # 确保冷却时间不低于最小值
			attack_timer.wait_time = attack_cooldown
			print(name, " 攻击冷却减少至: ", attack_cooldown)
		"range":  # 增加搜索范围
			search_radius += value
			print(name, " 搜索范围增加至: ", search_radius)
		"slow":  # 增加减速效果
			slow_effect = max(0.1, slow_effect - value)  # 减速效果是乘数，越小越慢
			print(name, " 减速效果增强至: ", (1.0 - slow_effect) * 100, "%")
		"freeze":  # 增加冰冻几率
			freeze_chance += value
			freeze_chance = min(freeze_chance, 0.7)  # 最大70%冰冻几率
			print(name, " 冰冻几率增加至: ", freeze_chance * 100, "%")
		_:
			print("未知属性升级: ", stat_name)
